package com.hbnu.serializable;

import java.io.*;

public class SerializableDemo {
    public static void main(String[] args) {
        String path = "C:"+File.separator+"Users"+File.separator+"TX"+File.separator+"IdeaProjects"+File.separator+"javalean"+File.separator+"src"+File.separator+"com"+File.separator+"hbnu"+File.separator+"serializable"+File.separator+"person.txt";
        File file = new File(path);

        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));

            Person person = new Person(1,"张三",8500.00);

            outputStream.writeObject(person);                                       //将对象序列化，通过writeObject方法

            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));

            Person person = (Person) inputStream.readObject();                  //将对象反序列化，这里是通过readObject()读取序列化后的数据，然后类型转换为person类实现

            System.out.println(person);                                         //这里要重写对象的toString方法，可以采用alt+insert快速重写

            inputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
